import { _decorator, Component, Node, Label, sp, tween, Vec3, UIOpacity, Color } from 'cc';
import { PlayerStatsModel, BattleResultData } from '../../../battle/Model';
import { PlayerType } from '../../../battle/Enums';
import { PlayerStatsManager } from './PlayerStatsManager';
import { PlayerStats } from './PlayerStats';
import { LOG } from '../../../ConsoleLogCtrl';
const { ccclass, property } = _decorator;

/**
 * 战斗结算界面
 * 显示战斗结束后的统计数据和胜负结果
 * 显示战斗双方玩家的统计信息
 */
@ccclass('BattleResultPanel')
export class BattleResultPanel extends Component {

    // 玩家1结果动画
    @property(sp.Skeleton)
    public player1ResultAnimation: sp.Skeleton = null;

    // 玩家2结果动画
    @property(sp.Skeleton)
    public player2ResultAnimation: sp.Skeleton = null;

    // 玩家1统计数据标签
    @property(Label)
    public player1Name: Label = null;

    @property(Label)
    public player1DamageDealt: Label = null;

    @property(Label)
    public player1DamageReceived: Label = null;

    @property(Label)
    public player1Healing: Label = null;

    @property(Label)
    public player1Kills: Label = null;

    @property(Label)
    public player1Deaths: Label = null;

    @property(Label)
    public player1Rmb: Label = null;

    @property(Label)
    public player1BaseHp: Label = null;

    @property(Label)
    public player1CmdFailCount: Label = null;

    // 玩家2统计数据标签
    @property(Label)
    public player2Name: Label = null;

    @property(Label)
    public player2DamageDealt: Label = null;

    @property(Label)
    public player2DamageReceived: Label = null;

    @property(Label)
    public player2Healing: Label = null;

    @property(Label)
    public player2Kills: Label = null;

    @property(Label)
    public player2Deaths: Label = null;

    @property(Label)
    public player2Rmb: Label = null;

    @property(Label)
    public player2BaseHp: Label = null;

    @property(Label)
    public player2CmdFailCount: Label = null;

    // 战斗结果信息标签
    @property(Label)
    public battleResultLabel: Label = null;

    private playerStatsManager: PlayerStatsManager = null;
    private battleResult: BattleResultData = null;

    onLoad() {
        this.playerStatsManager = PlayerStatsManager.getInstance();

        this.node.on(Node.EventType.TOUCH_END, this.onCloseButtonClicked, this);
    }

    /**
     * 显示战斗结果
     * @param battleResult 完整的战斗结果数据
     */
    public showBattleResult(battleResult: BattleResultData): void {
        this.battleResult = battleResult;

        // 更新战斗结果信息显示
        this.updateBattleResultDisplay();

        // 播放结果动画
        this.playResultAnimation();

        // 更新统计数据
        this.updateStatsDisplay();

        // 播放面板入场动画
        this.playPanelEnterAnimation();
    }

    /**
     * 更新战斗结果信息显示
     */
    private updateBattleResultDisplay(): void {
        if (!this.battleResultLabel || !this.battleResult) {
            return;
        }

        // 显示结束消息
        let resultText = `📝 ${this.battleResult.msg}`;

        // 设置Label的overflow属性来处理文本溢出
        this.battleResultLabel.overflow = Label.Overflow.RESIZE_HEIGHT;
        // 启用自动换行
        this.battleResultLabel.enableWrapText = true;

        this.battleResultLabel.string = resultText;
    }

    /**
     * 播放结果动画
     */
    private playResultAnimation(): void {
        const allPlayerStats = this.playerStatsManager.getAllPlayerStats();

        // 获取两个玩家的数据
        const player1Stats = allPlayerStats.find(stats => stats.getPlayerType() === PlayerType.PLAYER1);
        const player2Stats = allPlayerStats.find(stats => stats.getPlayerType() === PlayerType.PLAYER2);

        const player1Id = player1Stats?.getId();
        const player2Id = player2Stats?.getId();
        const winnerPlayerId = this.battleResult.winner;

        // 播放玩家1的结果动画
        this.playPlayerResultAnimation(
            this.player1ResultAnimation,
            player1Id === winnerPlayerId
        );

        // 播放玩家2的结果动画
        this.playPlayerResultAnimation(
            this.player2ResultAnimation,
            player2Id === winnerPlayerId
        );
    }

    /**
     * 为指定玩家播放结果动画
     * @param animation 动画组件
     * @param isWinner 是否为胜利者
     */
    private playPlayerResultAnimation(animation: sp.Skeleton, isWinner: boolean): void {
        if (!animation) return;

        if (isWinner) {
            // 播放胜利动画
            animation.setAnimation(0, 'dzz_cj_win', false);

            // 动画播放完成后循环播放待机动画
            animation.setCompleteListener(() => {
                // 播放胜利循环动画
                animation.setAnimation(0, 'dzz_cj_winloop', false);
            });
        } else {
            // 播放失败动画
            animation.setAnimation(0, 'dzz_cj_lose', false);

            // 动画播放完成后循环播放待机动画
            animation.setCompleteListener(() => {
                // 播放失败循环动画
                animation.setAnimation(0, 'dzz_cj_loseloop', false);
            });
        }
    }

    /**
     * 更新统计数据显示
     */
    private updateStatsDisplay(): void {
        const allPlayerStats = this.playerStatsManager.getAllPlayerStats();

        // 获取两个玩家的数据
        const player1Stats = allPlayerStats.find(stats => stats.getPlayerType() === PlayerType.PLAYER1);
        const player2Stats = allPlayerStats.find(stats => stats.getPlayerType() === PlayerType.PLAYER2);

        // 更新玩家1的统计数据
        if (player1Stats) {
            this.updatePlayerStatsDisplay(
                player1Stats.getId(),
                this.player1Name,
                this.player1DamageDealt,
                this.player1DamageReceived,
                this.player1Healing,
                this.player1Kills,
                this.player1Deaths,
                this.player1Rmb,
                this.player1BaseHp,
                this.player1CmdFailCount
            );
        }

        // 更新玩家2的统计数据
        if (player2Stats) {
            this.updatePlayerStatsDisplay(
                player2Stats.getId(),
                this.player2Name,
                this.player2DamageDealt,
                this.player2DamageReceived,
                this.player2Healing,
                this.player2Kills,
                this.player2Deaths,
                this.player2Rmb,
                this.player2BaseHp,
                this.player2CmdFailCount
            );
        }
    }

    /**
     * 更新单个玩家的统计数据显示
     * @param playerStats 玩家统计数据
     * @param nameLabel 玩家名称标签
     * @param damageDealtLabel 造成伤害标签
     * @param damageReceivedLabel 受到伤害标签
     * @param healingLabel 治疗量标签
     * @param killsLabel 击杀数标签
     * @param deathsLabel 死亡数标签
     * @param rmbLabel 经济值标签
     * @param baseHpLabel 基地血量标签
     * @param cmdFailCountLabel 命令失败数标签
     */
    private updatePlayerStatsDisplay(
        playerID: string,
        nameLabel: Label,
        damageDealtLabel: Label,
        damageReceivedLabel: Label,
        healingLabel: Label,
        killsLabel: Label,
        deathsLabel: Label,
        rmbLabel: Label,
        baseHpLabel: Label,
        cmdFailCountLabel: Label
    ): void {
        // 处理 playerStats 可能是 Map 或普通对象的情况
        let battleStat: PlayerStatsModel | undefined;
        if (this.battleResult.playerStats instanceof Map) {
            battleStat = this.battleResult.playerStats.get(playerID);
        } else {
            // 如果是普通对象，直接通过属性访问
            battleStat = (this.battleResult.playerStats as any)[playerID];
        }

        if (nameLabel) {
            nameLabel.string = playerID;
        }

        if (battleStat) {
            if (damageDealtLabel) {
                damageDealtLabel.string = `总伤害: ${battleStat.totalDamageDealt}`;
            }

            if (damageReceivedLabel) {
                damageReceivedLabel.string = `总受伤: ${battleStat.totalDamageReceived}`;
            }

            if (healingLabel) {
                healingLabel.string = `治疗量: ${battleStat.totalHealing}`;
            }

            if (killsLabel) {
                killsLabel.string = `击杀数: ${battleStat.kills}`;
            }

            if (deathsLabel) {
                deathsLabel.string = `死亡数: ${battleStat.deaths}`;
            }

            if (rmbLabel) {
                rmbLabel.string = `经济值: ${battleStat.rmb}`;
            }

            if (baseHpLabel) {
                baseHpLabel.string = `基地血: ${battleStat.baseHealth}`;
            }

            if (cmdFailCountLabel) {
                cmdFailCountLabel.string = `失败数: ${battleStat.commandFailCount}`;
            }
        } else {
            // 如果没有战斗统计数据，显示默认值
            if (damageDealtLabel) damageDealtLabel.string = '总伤害: 0';
            if (damageReceivedLabel) damageReceivedLabel.string = '总受伤: 0';
            if (healingLabel) healingLabel.string = '治疗量: 0';
            if (killsLabel) killsLabel.string = '击杀数: 0';
            if (deathsLabel) deathsLabel.string = '死亡数: 0';
            if (rmbLabel) rmbLabel.string = '经济值: 0';
            if (baseHpLabel) baseHpLabel.string = '基地血: 0';
            if (cmdFailCountLabel) cmdFailCountLabel.string = '失败数: 0';
        }
    }

    /**
     * 播放面板入场动画
     */
    private playPanelEnterAnimation(): void {

        // 设置初始状态
        this.node.setScale(0.5, 0.5, 1);
        const uiOpacity = this.node.getComponent(UIOpacity);
        if (uiOpacity) {
            uiOpacity.opacity = 0;
        }

        // 播放缩放和淡入动画
        tween(this.node)
            .to(0.3, { scale: new Vec3(1.1, 1.1, 1) }, { easing: 'backOut' })
            .to(0.1, { scale: new Vec3(1, 1, 1) })
            .start();

        if (uiOpacity) {
            tween(uiOpacity)
                .to(0.3, { opacity: 255 })
                .start();
        }
    }

    /**
     * 播放面板退出动画
     */
    private playPanelExitAnimation(callback?: () => void): void {
        if (!this.node) {
            if (callback) callback();
            return;
        }

        const uiOpacity = this.node.getComponent(UIOpacity);

        // 播放缩放和淡出动画
        tween(this.node)
            .to(0.2, { scale: new Vec3(0.8, 0.8, 1) })
            .call(() => {
                this.node.active = false;
                if (callback) callback();
            })
            .start();

        if (uiOpacity) {
            tween(uiOpacity)
                .to(0.2, { opacity: 0 })
                .start();
        }
    }

    /**
     * 关闭按钮点击事件
     */
    private onCloseButtonClicked(): void {
        this.playPanelExitAnimation(() => {
            // 可以在这里添加关闭后的逻辑，比如返回主菜单
            LOG.log('战斗结算面板已关闭');
        });
    }

    /**
     * 隐藏面板
     */
    public hidePanel(): void {
        this.playPanelExitAnimation();
    }

    /**
     * 重置面板状态
     */
    public resetPanel(): void {
        this.battleResult = null;
        this.node.active = false;

        // 重置战斗结果标签
        if (this.battleResultLabel) {
            this.battleResultLabel.string = '';
        }

        // 重置玩家1动画状态
        if (this.player1ResultAnimation) {
            this.player1ResultAnimation.clearTracks();
        }

        // 重置玩家2动画状态
        if (this.player2ResultAnimation) {
            this.player2ResultAnimation.clearTracks();
        }
    }

    onDestroy() {
        // 清理事件监听
        if (this.node) {
            this.node.off(Node.EventType.TOUCH_END, this.onCloseButtonClicked, this);
        }
    }
}